package com.song.rabbitmq.f_all;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 完整的声明式创建方式
 *      代码声明交换机、以及交换机绑定的队列
 */
public class Producer {

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接属性
        connectionFactory.setHost("121.41.53.91");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        Connection connection = null;
        Channel channel = null;
        try {
            // 1.从连接工厂中获取连接
            connection = connectionFactory.newConnection("direct路由模式-生产者");
            // 2: 从连接中获取通道channel
            channel = connection.createChannel();
            // 准备发送消息的内容
            String message = "你好，by direct路由模式的消息！！！完整的声明式创建方式：代码声明交换机、以及交换机绑定的队列";


            String exchangeName = "direct_message_exchange";
            String exchangeType = "direct";   // 交换机类型 direct/topic/fanout/headers
            // 声明交换机   持久化：交换机不会随着服务器重启造成丢失
            channel.exchangeDeclare(exchangeName, exchangeType, true);
            // 声明队列
            channel.queueDeclare("declare_queue1",true,false,false,null);
            channel.queueDeclare("declare_queue2",true,false,false,null);
            channel.queueDeclare("declare_queue3",true,false,false,null);
            // 绑定队列和交换机的关系
            channel.queueBind("declare_queue1",exchangeName,"order");
            channel.queueBind("declare_queue2",exchangeName,"order");
            channel.queueBind("declare_queue3",exchangeName,"course");


            channel.basicPublish(exchangeName,"order",null,message.getBytes());
            System.out.println("消息发送成功！");
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("发送消息出现异常...");
        } finally {
            // 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null  && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
